package com.jmp.api.controller;

import com.google.common.collect.Lists;
import com.jmp.api.dto.TemplateParamDto;
import com.jmp.api.service.TemplateCardFacadeService;
import com.jmp.api.service.TemplateCardService;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.*;
import com.jmp.base.enums.TemplateConfigTypeEnum;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.dto.DictDto;
import one.stand.mapper.TemplateConfigMapperExt;
import one.stand.mapper.TemplateMapperExt;
import one.stand.model.ResultModel;
import one.stand.model.Template;
import one.stand.model.TemplateConfig;
import one.stand.service.sys.SysDictValueService;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;
import java.util.List;

import static one.stand.util.ImageGenerateUtil.getUrlByBufferedImage;

@RestController
@Slf4j
public class TemplateController implements TemplateApi {
    @Autowired
    private SysDictValueService sysDictValueService;
    @Autowired
    private TemplateCardService templateCardService;
    @Autowired
    private TemplateCardFacadeService templateCardFacadeService;

    @Autowired
    private TemplateMapperExt templateMapperExt;
    @Autowired
    private TemplateConfigMapperExt templateConfigMapperExt;

    @Override
    public ResultModel save(@RequestBody TemplateSaveRequest request) {
        Template template = new Template();
        template.setId(request.getTemplate().getId());
        template.setName(request.getTemplate().getName());
        template.setImgUrl(request.getTemplate().getImgUrl());
        template.setCompanyId(request.getTemplate().getCompanyId());


        List<TemplateConfig> configList = Lists.newArrayList();
        boolean hasDiy = false;
        if (OneListUtil.isNotEmpty(request.getTemplateConfigs())) {
            for (TemplateSaveRequest.Config config : request.getTemplateConfigs()) {
                TemplateConfig templateConfig = new TemplateConfig();
                templateConfig.setType(config.getType());
                templateConfig.setPointX(config.getPointX());
                templateConfig.setPointY(config.getPointY());
                templateConfig.setImgWidth(config.getImgWidth());
                templateConfig.setImgHeight(config.getImgHeight());
                templateConfig.setImgUrl(config.getImgUrl());
                templateConfig.setFontStyle(config.getFontStyle());
                templateConfig.setFontSize(config.getFontSize());
                templateConfig.setFontCenter(config.getFontCenter());
                templateConfig.setFontColor(config.getFontColor());
                configList.add(templateConfig);

                if (config.getType() == TemplateConfigTypeEnum.IMG_DIY.getType()) {//自定义
                    AssertUtil.isFalse(hasDiy, ResultEnum.PARAM_CHECK, "只能有一个自定义图片组件");
                    hasDiy = true;

                    template.setImgWidth(config.getImgWidth());
                    template.setImgHeight(config.getImgHeight());

                    BufferedImage bimg = getUrlByBufferedImage(template.getImgUrl());//读取图片文件，得到BufferedImage对象
                    template.setImgUrlWidth(bimg.getWidth());
                    template.setImgUrlHeigth(bimg.getHeight());
                    template.setPositionWidth(config.getPointX());
                    template.setPositionHeight(config.getPointY());
                }
            }
        }

        Integer id = templateCardService.save(template, configList);
        templateCardFacadeService.remove(id);
        return ResultModel.success();
    }

    @Override
    public ResultModel<TemplateDetailResponse> detail(@RequestBody TemplateDetailRequest request) {

        Template template = templateMapperExt.selectByPrimaryKey(request.getTemplateId());
        List<TemplateConfig> configs = templateConfigMapperExt.selectByTemplateId(request.getTemplateId());

        List<TemplateDetailResponse.Config> configList = ConvertUtils.list(configs, config -> TemplateDetailResponse.Config.builder()
                .type(config.getType())
                .pointX(config.getPointX())
                .pointY(config.getPointY())
                .imgWidth(config.getImgWidth())
                .imgHeight(config.getImgHeight())
                .imgUrl(config.getImgUrl())
                .fontStyle(config.getFontStyle())
                .fontSize(config.getFontSize())
                .fontCenter(config.getFontCenter())
                .fontColor(config.getFontColor())
                .build());

        TemplateDetailResponse response = TemplateDetailResponse.builder()
                .id(template.getId())
                .name(template.getName())
                .imgUrl(template.getImgUrl())
                .configs(configList)
                .build();

        return ResultModel.success(response);
    }

    @Override
    public ResultModel up(@RequestBody TemplateUpRequest request) {
        templateCardService.up(request.getId(), request.getPushTitle(), request.getPushContent(), request.getLabels());
        return ResultModel.success();
    }

    @Override
    public ResultModel down(@RequestBody TemplateDownRequest request) {
        templateCardService.down(request.getId());
        return ResultModel.success();
    }

    @Override
    public ResultModel<TemplatePreviewResponse> preview(@RequestBody TemplatePreviewRequest request) {

        Template template = new Template();
        template.setId(request.getTemplate().getId());
        template.setName(request.getTemplate().getName());
        template.setImgUrl(request.getTemplate().getImgUrl());
        template.setCompanyId(request.getTemplate().getCompanyId());

        List<TemplateConfig> configList = ConvertUtils.list(request.getConfigs(), config -> {
            TemplateConfig templateConfig = new TemplateConfig();
            templateConfig.setType(config.getType());
            templateConfig.setPointX(config.getPointX());
            templateConfig.setPointY(config.getPointY());
            templateConfig.setImgWidth(config.getImgWidth());
            templateConfig.setImgHeight(config.getImgHeight());
            templateConfig.setImgUrl(config.getImgUrl());
            templateConfig.setFontStyle(config.getFontStyle());
            templateConfig.setFontSize(config.getFontSize());
            templateConfig.setFontCenter(config.getFontCenter());
            templateConfig.setFontColor(config.getFontColor());
            return templateConfig;
        });

        TemplateParamDto paramDto = TemplateParamDto.builder()
                .cardId(request.getCardId())
                .goodsId(request.getGoodsId())
                .articleId(request.getArticleId())
                .roomId(request.getRoomId())
                .diyImg(request.getDiyImg())
                .diyUrl(request.getDiyUrl())
                .articleH5Url(request.getArticleH5Url())
                .groupId(request.getGroupId())
                .groupPrice(request.getGroupPrice())
                .groupH5Url(request.getGroupH5Url())
                .build();
        String imageUrl = templateCardFacadeService.preview(template, configList, paramDto);
        TemplatePreviewResponse response = TemplatePreviewResponse.builder().imageUrl(imageUrl).build();
        return ResultModel.success(response);
    }

    @Override
    public ResultModel<TemplateCreateResponse> create(@RequestBody TemplateCreateRequest request) {
        TemplateParamDto paramDto = TemplateParamDto.builder()
                .cardId(request.getCardId())
                .goodsId(request.getGoodsId())
                .articleId(request.getArticleId())
                .diyImg(request.getDiyImg())
                .diyUrl(request.getDiyUrl())
                .build();
        String imageUrl = templateCardFacadeService.create(request.getTemplateId(), paramDto);
        TemplateCreateResponse response = TemplateCreateResponse.builder().imageUrl(imageUrl).build();
        return ResultModel.success(response);
    }

    @Override
    public ResultModel<TemplateGetResponse> get(@RequestBody TemplateGetRequest request) {
        TemplateParamDto paramDto = TemplateParamDto.builder()
                .cardId(request.getCardId())
                .goodsId(request.getGoodsId())
                .articleId(request.getArticleId())
                .backgroundUrl(request.getBackgroundUrl())
                .configExclude(request.getConfigExclude())
                .articleH5Url(request.getArticleH5Url())
                .build();
        String imageUrl = templateCardFacadeService.get(request.getTemplateId(), paramDto);
        TemplateGetResponse response = TemplateGetResponse.builder().imageUrl(imageUrl).build();
        return ResultModel.success(response);
    }

    @Override
    public ResultModel<TemplateGetResponse> get2(@RequestBody TemplateGet2Request request) {
        DictDto dictDto = sysDictValueService.get2(SysDictValueService.Type.CONFIG_TEMPLATE, request.getTemplateType().name());
        AssertUtil.nonNull(dictDto, "模板配置错误");
        Integer templateId = dictDto.getValueInteger();
        AssertUtil.nonNull(templateId, "模板配置错误");

        TemplateParamDto paramDto = TemplateParamDto.builder()
                .cardId(request.getCardId())
                .goodsId(request.getGoodsId())
                .articleId(request.getArticleId())
                .roomId(request.getRoomId())
                .backgroundUrl(request.getBackgroundUrl())
                .configExclude(request.getConfigExclude())
                .articleH5Url(request.getArticleH5Url())
                .groupId(request.getGroupId())
                .groupPrice(request.getGroupPrice())
                .groupH5Url(request.getGroupH5Url())
                .build();
        String imageUrl = templateCardFacadeService.get(templateId, paramDto);
        TemplateGetResponse response = TemplateGetResponse.builder().imageUrl(imageUrl).build();
        return ResultModel.success(response);
    }

    @Override
    public ResultModel updateByCard(@RequestBody TemplateUpdateByCardRequest request) {
        templateCardFacadeService.removeByCard(request.getCardId());
        return ResultModel.success();
    }

    @Override
    public ResultModel removeArticle(@RequestBody TemplateRemoveArticleRequest request) {
        templateCardFacadeService.removeByArticle(request.getArticleId());
        return ResultModel.success();
    }

    @Override
    public ResultModel<TemplateListVo> list(@RequestBody TemplateListDto request) {

        TemplateListVo vo = templateCardFacadeService.getList(request);
        return ResultModel.success(vo);
    }

    @Override
    public ResultModel listAsync(@RequestBody TemplateListDto request) {

        templateCardFacadeService.getListAsync(request);

        return ResultModel.success();
    }
}
